package Array;

/**
 * @auther wangchenghao
 * @date 2021/6/2
 * 买卖股票的最佳时机 II
 **/
public class test2 {
    public static int maxProfit(int[] prices) {
        int sum = 0;
        int i=0;
        while (i<prices.length-1){
            int in = prices[i];
            int j = i + 1;
            if (prices[j] > prices[i]) {
                int out = prices[j];
                while (j < prices.length) {
                    if (prices[j] < out) {
                        break;
                    } else {
                        out = prices[j];
                        j++;
                    }
                }
                int earn = out - in;
                sum += earn;
                i = j - 1;
            } else {
                i = j;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] price = {6,1,3,2,4,7};
        System.out.println("maxProfit(price) = " + maxProfit(price));
    }

    /**
     * @param prices
     * @return
     * 贪心算法 局部最优到全局最优
     */
    public static int maxProfits(int[] prices) {
        int ans = 0;
        int n = prices.length;
        for (int i = 1; i < n; ++i) {
            ans += Math.max(0, prices[i] - prices[i - 1]);
        }
        return ans;

    }
}
